package org.caijin.springzookeeper.Curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.CuratorWatcher;
import org.apache.curator.framework.recipes.cache.*;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.data.Stat;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CuratorDemo {
    public final static String cluster_connection = "192.168.88.100:2181,192.168.88.101:2181,192.168.88.102:2181";
    public static void main(String[] args) throws Exception {
        // 构建客户端
        CuratorFramework curatorFramework = CuratorFrameworkFactory.builder()
                .connectString(cluster_connection)
                .retryPolicy(new ExponentialBackoffRetry(1000, 3))
                .build();
        // 启动客户端
        curatorFramework.start();

        String path = "/user";

        // 检查节点是否存在
        Stat stat = curatorFramework.checkExists().forPath(path);
        if (stat != null) {
            // 删除节点
            curatorFramework.delete().forPath(path);
        }
        // 创建节点
        curatorFramework.create()
                .creatingParentsIfNeeded()
                .withMode(CreateMode.PERSISTENT)
                .forPath(path);

        // 注册节点监听器
        curatorFramework.getData()
                .usingWatcher(new CuratorWatcher() {
                    @Override
                    public void process(WatchedEvent watchedEvent) throws Exception {
                        byte[] bytes = curatorFramework.getData().forPath(path);
                        System.out.println("Node data Changed: " + new String(bytes));
                    }
                })
                .forPath(path);

        // 更新节点信息
        curatorFramework.setData()
                .forPath(path, "Update Date".getBytes());

        stat = new Stat();
        // 查询节点数据
        byte[] data = curatorFramework.getData().storingStatIn(stat).forPath(path);
        System.out.println(new String(data));

        ExecutorService executorService = Executors.newSingleThreadExecutor();
        // 异步处理，可以指定线程池
        curatorFramework.getData().inBackground((item1,item2) -> {
            System.out.println("background"+item1+","+item2);
            System.out.println(item2.getStat());
        },executorService).forPath(path);

        // 创建节点缓存,用于监听指定节点变化
        final NodeCache nodeCache = new NodeCache(curatorFramework, path);
        // 启动NodeCache并立即从服务器获取最新数据
        nodeCache.start();
        // 注册节点变化监听器
        nodeCache.getListenable().addListener(new NodeCacheListener() {
            @Override
            public void nodeChanged() throws Exception {
                byte[] data = curatorFramework.getData().forPath(path);
                System.out.println("Node data Changed: " + new String(data));
            }
        });

        // 创建子节点缓存
        PathChildrenCache pathChildrenCache = new PathChildrenCache(curatorFramework, path, true);
        pathChildrenCache.start();
        pathChildrenCache.getListenable().addListener(new PathChildrenCacheListener() {

            @Override
            public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent event) throws Exception {
                if(event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED) {
                    ChildData data = event.getData();
                    System.out.println("child added: " + data.getPath());
                }
                if(event.getType() == PathChildrenCacheEvent.Type.CHILD_REMOVED) {
                    ChildData data = event.getData();
                    System.out.println("child removed: " + data.getPath());
                }
                if(event.getType() == PathChildrenCacheEvent.Type.CHILD_UPDATED) {
                    ChildData data = event.getData();
                    System.out.println("child updated: " + data.getPath());
                }

            }
        });






    }


}
